package geek.talk.wzmresolution;

import android.app.Service;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.os.Handler;
import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Toast;

public class FloatWindowService extends Service {
    private WindowManager windowManager;
    private View floatView;
    private Handler handler = new Handler();
    
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
        
        floatView = LayoutInflater.from(this).inflate(R.layout.float_window, null);
        
        WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
            WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
            PixelFormat.TRANSLUCENT);
        params.gravity = Gravity.TOP | Gravity.START;
        params.x = 100;
        params.y = 100;
        
        floatView.setOnTouchListener(new FloatViewTouchListener(params, windowManager));
        
        floatView.setOnClickListener(v -> {
            if (System.currentTimeMillis() - lastClickTime < 300) {
                changeResolution();
            }
            lastClickTime = System.currentTimeMillis();
        });
        
        windowManager.addView(floatView, params);
    }
    
    private long lastClickTime = 0;
    
    private void changeResolution() {
        try {
            Process process = Runtime.getRuntime().exec("su");
            process.getOutputStream().write(("wm size 800x360\n").getBytes());
            process.getOutputStream().flush();
            
            handler.postDelayed(() -> {
                try {
                    Process resetProcess = Runtime.getRuntime().exec("su");
                    resetProcess.getOutputStream().write(("wm size reset\n").getBytes());
                    resetProcess.getOutputStream().flush();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, 10000);
            
        } catch (Exception e) {
            Toast.makeText(this, "需要root权限", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (floatView != null) {
            windowManager.removeView(floatView);
        }
    }
}